<template>
  <section class="todoapp">
    <header class="header">
      <h1>Vue3 todos</h1>
      <input
        type="text"
        placeholder="想干的事"
        class="new-todo"
        @keydown.enter="addTodo"
        v-model="newTodo"
      />
    </header>

    <section class="main">
      <ul class="todo-list">
        <li class="todo" v-for="item in todos" :key="item.id">
          <div class="view">
            <label for="">{{ item.title }}</label>
            <button class="destroy" @click="delTodo(item.id)"></button>
          </div>
        </li>
      </ul>
    </section>
  </section>
</template>

<script>
import { toRefs, reactive } from "@vue/reactivity";
export default {
  name: "App",
  setup() {
    function addTodo() {
      if (this.newTodo) {
        let newTodo = {
          id: "" + this.todos.length,
          title: this.newTodo.trim(),
          completed: false,
        };
        this.todos.push(newTodo);
        this.newTodo = "";
      }
    }
    function delTodo(id) {
      console.log(id);
      let index = this.todos.findIndex((x) => x.id == id);
      this.todos.splice(index,1)
    }
    const state = reactive({
      todos: [
        {
          id: "1",
          title: "吃饭",
          completed: false,
        },
        {
          id: "2",
          title: "睡觉",
          completed: false,
        },
      ],
      newTodo: "",
    });

    return { ...toRefs(state), addTodo, delTodo };
  },
};
</script>

<style>
</style>
